<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class BalanceNotice extends Model
{
    public function store(): HasOne
    {
        return $this->hasOne(Store::class, "id", "store_id");
    }

    public function supplier(): HasOne
    {
        return $this->hasOne(Supplier::class, "id", "supplier_id");
    }

    public function admin(): HasOne
    {
        return $this->hasOne(Admin::class, "id", "aid");
    }

    public function getPage(): array
    {
        $admin = request()->admin;
        $params = request()->param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 50;
        $data = $this->with(['store', 'supplier', 'admin'])->when(!empty($params['store_id']), function ($query) use ($params) {
            $query->where('store_id', $params['store_id']);
        })->when(!empty($params['supplier_id']), function ($query) use ($params) {
            $query->where('supplier_id', $params['supplier_id']);
        })->when(!empty($admin) && $admin['is_admin'] == 2 && empty($params['store_id']) && empty($params['supplier_id']), function ($query) {
            $query->where('store_id', '<>', 13);
        })->when(!empty($params['type']), function ($query) use ($params) {
            $query->where('type', $params['type']);
        })->when(!empty($params['create_time']), function ($query) use ($params) {
            $query->whereBetween('create_time', [$params['create_time'][0] . " 00:00:00", $params['create_time'][1] . " 23:59:59"]);
        })->where(['type' => [1, 3]])->order(['create_time' => 'desc'])->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total'], 'totalPage' => $data['last_page']];
    }

    public function download(): array
    {
        $data = $this->getPage();
        $result = array_map(function ($item) {
            return [
                $item['store']['name'],
                $item['supplier']['name'],
                ($item['type'] == 1 ? '+' : '-') . bcdiv($item['number'], 100, 2),
                $item['content'],
                $item['admin']['account'],
                $item['create_time'],
            ];
        }, $data['lst']);
        $totalPage = $data['totalPage'];
        $header = [
            '门店名称',
            '渠道名称',
            '金额',
            '备注',
            '操作人',
            '时间',
        ];
        $title = ["门店充值记录"];
        $file = "门店充值记录";
        return compact("result", "header", "title", "totalPage", "file");
    }
}
